#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import multiprocessing
import time
import sys
from datetime import datetime

repo_url = os.environ.get("KERNEL_CI_REPO_URL")
branch = os.environ.get("KERNEL_CI_REPO_BRANCH")
pr_id = os.environ.get("KERNEL_CI_PR_ID") if os.environ.get("KERNEL_CI_PR_ID") else ""
script = sys.argv[1]
builder1 = os.environ.get("YES_BUILDER")
builder2 = os.environ.get("DEF_BUILDER")
if not builder2:
    builder2 = os.environ.get("REMOTE_HOST")
builder3 = ""
cases = os.environ.get("testcases")


def build_kernel(host, configs):
    return_code = 0
    for config in configs:
        log_file = "/tmp/anck_{}.log".format(config)
        print("BUILD CONFIG - {}: write log to {}".format(config, log_file))
        if host:
            cmd = "ssh {} \"bash {} {} {} {} {}\" > {} 2>&1".format(host, script, config, repo_url, branch, pr_id, log_file)
        else:
            cmd = "bash {} {} {} {} {} > {} 2>&1".format(script, config, repo_url, branch, pr_id, log_file)
        print("CMD: {}".format(cmd))
        return_code += os.system(cmd)
        print("[{}]: Finished {} with return code {}".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), config, return_code))
        print("-"*80)
    return return_code


t_before = time.time()
group1 = []
group2 = []
group3 = []
if cases:
    if "allyesconfig" in cases:
        group1.append("build_allyes_config")
    if "defconfig" in cases:
        group2.append("build_anolis_defconfig")
    if "debugconfig" in cases:
        group2.append("build_anolis_debug_defconfig")
    if "checkconfig" in cases:
        group3.append("check_Kconfig")
    if "allnoconfig" in cases:
        group3.append("build_allno_config")
    if "rpmbuild" in cases:
        group3.append("anck_rpm_build")
else:
    group1 = ["build_allyes_config"]
    group2 = ["build_anolis_defconfig", "build_anolis_debug_defconfig"]
    group3 = ["check_Kconfig", "build_allno_config", "anck_rpm_build"]

tasks = []
if group1:
    p1 = multiprocessing.Process(target=build_kernel, name="group1", args=(builder1, group1))
    tasks.append(p1)
if group2:
    p2 = multiprocessing.Process(target=build_kernel, name="group2", args=(builder2, group2))
    tasks.append(p2)
if group3:
    p3 = multiprocessing.Process(target=build_kernel, name="group3", args=(builder3, group3))
    tasks.append(p3)

for t in tasks:
    t.start()

pro_no = len(multiprocessing.active_children())
while(pro_no > 1):
    time.sleep(10)
    pro_no = len(multiprocessing.active_children())

for t in tasks:
    t.join()
t_after = time.time()
print("="*80)
print("Total time spend: {}".format(t_after-t_before))
